package com.neusoft.hifly.push.sms.gateway.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.neusoft.hifly.core.log.Log;
import com.neusoft.hifly.push.sms.gateway.dao.ISMSToDoDao;
import com.neusoft.hifly.push.sms.gateway.pojo.SMSToDoObj;
import com.neusoft.hifly.push.sms.gateway.utils.SMSDBUtil;

/**
 * Title: 短信服务
 * <p>
 * Description: 发送短信
 * <p>
 * Copyright: 2019
 * <p>
 * Company: 东软汉枫
 *
 * @author lh_neu
 * @version 1.0.0
 */
@Repository
public class SMSToDoDaoImpl implements ISMSToDoDao {
	@Autowired
	private SMSDBUtil smsDBUtil;

	/**
	 * 保存对象
	 *
	 * @param obj
	 *            对象
	 * @return 是否操作成功
	 */
	@Override
	public boolean save(final SMSToDoObj obj) {
		final StringBuffer sql = new StringBuffer("INSERT INTO " + SMSToDoObj.TABLE_NAME + " (" + SMSToDoObj.TABLE_ID
				+ ", " + SMSToDoObj.TABLE_LOGIC_ID + ",  RECEIVE_NUM, RECEIVE_NAME, MSG, SEND_TIME, "
				+ " SEND_NAME, PRIORITY, APP_INFO, OBJ_ID, RETURN_URL, "
				+ " RETURN_PARAMS, UPDATE_TIME, EXT1, EXT2, EXT3, EXT4, EXT5) "
				+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
		Log.error(sql.toString());
		PreparedStatement pt = null;
		final Connection conn = smsDBUtil.getDBConnection();
		try {
			pt = conn.prepareStatement(sql.toString());
			int i = 1;
			pt.setLong(i++, obj.getId());
			pt.setLong(i++, obj.getLogicId());
			pt.setString(i++, obj.getReceiveNum());
			pt.setString(i++, obj.getReceiveName());
			pt.setString(i++, obj.getMsg());
			if (obj.getSendTime() != null) {
				pt.setTimestamp(i++, Timestamp.valueOf(obj.getSendTime()));
			} else {
				pt.setTimestamp(i++, null);
			}
			pt.setString(i++, obj.getSendName());
			pt.setString(i++, obj.getPriority());
			pt.setString(i++, obj.getAppInfo());
			pt.setLong(i++, obj.getObjId());
			pt.setString(i++, obj.getReturnUrl());
			pt.setString(i++, obj.getReturnParams());

			if (obj.getUpdateTime() != null) {
				pt.setTimestamp(i++, Timestamp.valueOf(obj.getUpdateTime()));
			} else {
				pt.setTimestamp(i++, null);
			}
			pt.setString(i++, obj.getExt1());
			pt.setString(i++, obj.getExt2());
			pt.setString(i++, obj.getExt3());
			pt.setString(i++, obj.getExt4());
			pt.setString(i, obj.getExt5());
			final int executeUpdate = pt.executeUpdate();
			if (executeUpdate != 0) {
				return true;
			}
		} catch (final SQLException e) {
			e.printStackTrace();
		} finally {
			if (pt != null) {
				try {
					pt.close();
				} catch (final SQLException e) {
					e.printStackTrace();
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (final SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return false;
	}

}
